#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/select.h>

void sys_error(const char *msg)
{
    perror(msg);
    exit(1);
}
int kbhit()
{
    struct timeval tv;
    fd_set readfds;
    tv.tv_sec = 0;
    tv.tv_usec = 0;
    FD_ZERO(&readfds);
    FD_SET(STDIN_FILENO, &readfds);
    select(STDIN_FILENO + 1, &readfds, NULL, NULL, &tv);
    return FD_ISSET(STDIN_FILENO, &readfds);
}
int main(int argc, char const *argv[])
{
    int fd = open("/home/lckfb/Documents/fifo.fifo", O_RDONLY);
    if (fd == -1)
        sys_error("open fifo failed");

    int len = 0;
    char buf[1024];
    char input;
    printf("Press 'q' to quit.\n");
    while (1)
    {
        len = read(fd, buf, sizeof(buf));
        write(STDOUT_FILENO, buf, len);
        if (kbhit())
        {
            input = getchar();
            if (input == 'q')
            {
                break; // 如果输入的是 'q'，则退出循环
            }
        }
        sleep(1);
    }
    close(fd);
    return 0;
}
